﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Microsoft.Office.OneNote
{
    internal static class PathHelper
    {
        private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();

        public static bool ContainsInvalidFileNameChars(string path)
        {
            return (path.IndexOfAny(InvalidFileNameChars)) > -1;
        }

        public static bool IsDescendantOf(string path, string potentialAncestor)
        {
            return IsAncestorOf(potentialAncestor, path);
        }

        public static bool IsAncestorOf(string path, string potentialDescendant)
        {
            string relativePath;

            return IsAncestorOf(path, potentialDescendant, out relativePath);
        }

        public static bool IsAncestorOf(string path, string potentialDescendant, out string relativePath)
        {
            Contract.RequiresNotNullNorEmpty(path, "path");
            Contract.RequiresNotNullNorEmpty(potentialDescendant, "potentialDescendant");

            path = EnsureTrailingSlash(path);
            potentialDescendant = EnsureNoTrailingSlash(potentialDescendant);

            if (potentialDescendant.StartsWith(path, StringComparison.OrdinalIgnoreCase))
            {
                relativePath = potentialDescendant.Substring(path.Length);
                return true;
            }

            relativePath = null;
            return false;
        }

        private static string EnsureNoTrailingSlash(string path)
        {
            if (path[path.Length - 1] == '\\')
            {
                return path.Substring(path.Length - 1);
            }

            return path;
        }


        private static string EnsureTrailingSlash(string path)
        {
            if (path[path.Length - 1] == '\\')
            {
                return path;
            }

            return path + '\\';
        }
    }
}
